<template>
	<view class="page">
		<view class="form-box">
			<u-form ref="uForm" :model="model" :rules="rules" labelWidth="150rpx" labelAlign="left" labelPosition="left">
				<u-form-item label="头像" borderBottom required>
					<button class="avatar-box u-reset-button" open-type="chooseAvatar" @chooseavatar="onChooseAvatar">
						<u-avatar :src="model.icon" :default-url="defaultImg" size="80rpx"></u-avatar>
						<text v-if="!avatarLoading" class="avatar-btn">点击选择头像</text>
						<u-loading-icon v-else size="28rpx"></u-loading-icon>
					</button>
				</u-form-item>
				<u-form-item label="姓名" prop="name" borderBottom required>
					<u-input maxlength="10" v-model="model.name" border="none" :customStyle="inputCustomStyle"
						placeholder='请输入姓名'></u-input>
				</u-form-item>
				<u-form-item label="手机" prop="mobile" borderBottom required>
					<u-input maxlength="20" v-model="model.mobile" border="none" :customStyle="inputCustomStyle"
						placeholder='请输入手机号'></u-input>
				</u-form-item>
				<u-form-item label="简介" borderBottom>
					<u-input maxlength="40" v-model="model.profile" border="none" :customStyle="inputCustomStyle"
						placeholder='请输入简介'></u-input>
				</u-form-item>
			</u-form>
		</view>

		<view class="submit-box">
			<u-button color="#276AEE" throttleTime="500" :customStyle="{height:'88rpx',fontSize: '30rpx'}" :loading="loading"
				@click="submit">加入群聊</u-button>
		</view>

		<view class="home-box" @tap="gotoHome">
			<u-image width="250rpx" height="250rpx"
				src="https://file.casugn.com/storecompcard//ZxEqTL9Ij86s7e45ed65ad93efdaed999ee6b01bc5b7_1666764803907.png"></u-image>
			<view class="home-title">点击进入小程序</view>
		</view>
	</view>
</template>

<script>
	import { mapGetters } from 'vuex'

	export default {
		data() {
			return {
				defaultImg: 'https://file.casugn.com/storecompcard//GFnT1GaT8CD9089ddbabd7d7c2180f52b649e7945ba7_1661907569321.png',
				inputCustomStyle: { padding: '10rpx 0' },
				rules: {
					icon: [{
						required: true,
						message: '请上传头像',
						trigger: ['change', 'blur'],
					}],
					name: [{
						required: true,
						message: '请输入姓名',
						trigger: ['change', 'blur'],
					}],
					mobile: [{
							required: true,
							message: '请输入手机号',
							trigger: ['change', 'blur'],
						},
						{
							validator: (rule, value, callback) => {
								return uni.$u.test.mobile(value);
							},
							message: '手机号码不正确',
							trigger: ['change', 'blur'],
						}
					]
				},

				groupId: '',
				openId: '',
				model: {
					icon: "",
					name: '',
					mobile: '',
					profile: ''
				},
				avatarLoading: false,
				loading: false,
			}
		},
		computed: {
			...mapGetters(['userInfo']),
		},
		async onLoad(option) {
			console.log('==============joinQuickGroup================', option);
			console.log('=========userInfo==============', this.userInfo);
			this.groupId = option.id || decodeURIComponent(option.scene)
			this.openId = await this.getOpenId()

			// 判断是否已加入群聊,如果是,直接跳转进群聊详情
			this.judgeJoinQuickGroup()

			// 获取已存在用户的信息并回显
			if (this.openId) {
				this.getUserInfoByOpenId()
			}
		},
		onReady() {
			// 如果需要兼容微信小程序，并且校验规则中含有方法等，只能通过setRules方法设置规则
			this.$refs.uForm.setRules(this.rules)
		},
		methods: {
			gotoHome() {
				uni.switchTab({ url: '/pages/card/card' })
			},
			getOpenId() {
				const that = this
				return new Promise(async (resolve, reject) => {
					if (that.$store.getters.openId) {
						resolve(that.$store.getters.openId)
					} else {
						let res = await that.$store.dispatch('getOpenId')
						resolve(res.openid || '')
					}
				});
			},
			async judgeJoinQuickGroup() {
				let params = {
					openId: this.openId,
					groupId: this.groupId
				}
				let res = await this.$api.judgeJoinQuickGroupByOpenId(params)
				if (res) {
					uni.redirectTo({
						url: '/pagesCard/quickGroupDetail/quickGroupDetail?id=' + this.groupId
					})
				}
			},
			async getUserInfoByOpenId() {
				let params = {
					openId: this.openId
				}
				let res = await this.$api.queryCurrentCardByOpenId(params)
				if (res.success && res.result && res.result.id) {
					this.model.icon = res.result.head
					this.model.name = res.result.name
					this.model.mobile = res.result.mobile
				}
			},
			async onChooseAvatar(e) {
				const { avatarUrl } = e.detail
				this.avatarLoading = true
				let imgUrl = await this.uploadFilePromise(avatarUrl)
				if (imgUrl) {
					this.model.icon = imgUrl
					this.$refs.uForm.validateField(['icon'])
					this.avatarLoading = false
				} else {
					this.avatarLoading = false
				}
			},
			uploadFilePromise(url) {
				return new Promise((resolve, reject) => {
					let a = uni.uploadFile({
						url: this.$baseConfig.uploadUrl + '/casugn-system/sys/common/upload',
						filePath: url,
						name: 'file',
						success: (res) => {
							let data = JSON.parse(res.data)
							if (data.success) {
								resolve(data.message)
							}
						}
					});
				})
			},
			submit() {
				const that = this
				this.$refs.uForm.validate().then(async () => {
					//如果没有名片, 保存提交信息,在聊天室里使用
					if (!that.userInfo || !that.userInfo.id) {
						let quickJoinGroupUserInfo = {
							openId: that.openId,
							head: that.model.icon,
							name: that.model.name,
						}
						that.$store.commit('quickJoinGroupUserInfo', quickJoinGroupUserInfo)
					}

					let params = {
						...that.model,
						groupId: that.groupId,
						openId: that.openId,
					}
					that.loading = true
					let res = await that.$api.addQuickGroupMembers(params)
					if (res.success) {
						that.loading = false
						uni.redirectTo({
							url: '/pagesCard/quickGroupDetail/quickGroupDetail?id=' + that.groupId
						})
					} else {
						uni.showToast({ title: res.message || "加入群聊失败！", icon: 'none' });
						that.loading = false
					}
				}).catch(err => {
					console.log(err, 'err');
				})

			}
		}
	}
</script>

<style lang="scss" scoped>
	.page {
		padding-bottom: constant(safe-area-inset-bottom);
		padding-bottom: env(safe-area-inset-bottom);
	}

	::v-deep.form-box {
		padding: 32rpx;

		.u-form-item__body__left__content__required {
			position: relative !important;
			left: 0 !important;
			padding-right: 10rpx !important;
		}

		.avatar-box {
			margin: 0;

			display: flex;
			align-items: center;

			.avatar-btn {
				margin-left: 20rpx;
			}
		}
	}

	.submit-box {
		padding: 16rpx 48rpx;
		box-sizing: border-box;
	}

	.home-box {
		width: fit-content;
		margin: 32rpx auto 0;

		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;

		.home-title {
			font-size: 24rpx;
			color: #666;
			line-height: 32rpx;
			text-align: center;
		}
	}
</style>
